#pragma once

#include <sys/epoll.h>
#include <unistd.h>
#include <cstring>
#include "Err.hpp"
#include "log.hpp"

const static int default_size = 128;
const static int default_epfd = -1;

class epoller
{
public:
    epoller(int epfd = default_epfd): _epfd(epfd)
    {}

    int GetFd()
    {
        return _epfd;
    }

    void Create()
    {
        _epfd = epoll_create(default_size);
        if(_epfd < 0)
        {
            LogMessage(Fatal, "Epoll create error, errno: %d, errno_string: %s", errno, strerror(errno));
            exit(EPOLL_CREATE_ERR);
        }
    }

    int Wait(struct epoll_event* events, int N, int timeout)
    {
        return epoll_wait(_epfd, events, N, timeout);
    }

    void CtlEvent(int fd, int op, uint32_t event)
    {
        struct epoll_event ev;
        ev.data.fd = fd;
        ev.events = event;

        epoll_ctl(_epfd, op, fd, &ev);
    }

    void DelEvent(int fd)
    {
        epoll_ctl(_epfd, EPOLL_CTL_DEL, fd, nullptr);
    }

    void Close()
    {
        close(_epfd);
    }

    ~epoller()
    {
        if(_epfd != default_epfd)
            close(_epfd);
    }
private:
    int _epfd;
};